/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.mgt.server.service.power.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.iwindplus.boot.domain.enums.BizCodeEnum;
import com.iwindplus.boot.domain.enums.EnableStatusEnum;
import com.iwindplus.boot.domain.exception.BizException;
import com.iwindplus.boot.redis.manager.SerialNumManager;
import com.iwindplus.mgt.domain.constant.MgtConstant;
import com.iwindplus.mgt.domain.dto.power.DepartmentDTO;
import com.iwindplus.mgt.domain.dto.power.DepartmentEditDTO;
import com.iwindplus.mgt.domain.dto.power.DepartmentSaveDTO;
import com.iwindplus.mgt.domain.enums.MgtCodeEnum;
import com.iwindplus.mgt.domain.enums.MgtCodePrefixEnum;
import com.iwindplus.mgt.domain.vo.power.DepartmentBaseTreeCheckedVO;
import com.iwindplus.mgt.domain.vo.power.DepartmentExtendVO;
import com.iwindplus.mgt.domain.vo.power.DepartmentVO;
import com.iwindplus.mgt.server.mapper.power.DepartmentMapper;
import com.iwindplus.mgt.server.model.power.DepartmentDO;
import com.iwindplus.mgt.server.service.power.DepartmentService;
import com.iwindplus.mgt.server.service.power.UserDepartmentService;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 部门业务层接口实现类.
 *
 * @author zengdegui
 * @since 2018/9/1
 */
@Service
@CacheConfig(cacheNames = {"department"})
@Transactional(rollbackFor = Exception.class)
public class DepartmentServiceImpl extends JoinCrudRepository<DepartmentMapper, DepartmentDO> implements DepartmentService {

    @Resource
    private SerialNumManager serialNumManager;

    @Resource
    private UserDepartmentService userDepartmentService;

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"department"}, allEntries = true),
            @CacheEvict(cacheNames = {"userDepartment"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true)
        }
    )
    @Override
    public boolean save(DepartmentSaveDTO entity) {
        entity.setStatus(EnableStatusEnum.ENABLE);
        entity.setBuildInFlag(Boolean.FALSE);
        this.getNameIsExist(entity.getName().trim(), entity.getOrgId(), entity.getParentId());
        if (CharSequenceUtil.isBlank(entity.getCode())) {
            entity.setCode(this.serialNumManager.getSerialNum(MgtCodePrefixEnum.DEPARTMENT_PREFIX.getValue()));
        }
        this.getCodeIsExist(entity.getCode().trim(), entity.getOrgId(), entity.getParentId());
        entity.setSeq(this.getNextSeq(entity.getOrgId(), entity.getParentId()));
        entity.setLevel(this.getLevel(entity.getOrgId(), entity.getParentId()));
        final DepartmentDO model = BeanUtil.copyProperties(entity, DepartmentDO.class);
        super.save(model);
        entity.setId(model.getId());
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"department"}, allEntries = true),
            @CacheEvict(cacheNames = {"userDepartment"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true)
        }
    )
    @Override
    public List<DepartmentVO> saveBatchInit(List<DepartmentDTO> entities) {
        List<DepartmentVO> resultList = new ArrayList<>(10);
        AtomicReference<Integer> seq = new AtomicReference<>();
        AtomicBoolean flag = new AtomicBoolean(true);
        List<DepartmentDTO> saveList = new ArrayList<>(10);
        List<DepartmentDTO> existList = new ArrayList<>(10);
        entities.forEach(entity -> {
            final LambdaQueryWrapper<DepartmentDO> queryWrapper = Wrappers.lambdaQuery(DepartmentDO.class)
                .eq(DepartmentDO::getName, entity.getName())
                .eq(DepartmentDO::getOrgId, entity.getOrgId());
            if (Objects.nonNull(entity.getParentId())) {
                queryWrapper.eq(DepartmentDO::getParentId, entity.getParentId());
            }
            final DepartmentDO data = super.getOne(queryWrapper);
            if (Objects.isNull(data)) {
                if (flag.get()) {
                    seq.set(this.getNextSeq(entity.getOrgId(), entity.getParentId()));
                    flag.set(false);
                }
                entity.setSeq(seq.getAndSet(seq.get() + 1));
                saveList.add(entity);
            } else {
                final DepartmentDTO dto = BeanUtil.copyProperties(data, DepartmentDTO.class);
                existList.add(dto);
            }
        });
        if (CollUtil.isNotEmpty(saveList)) {
            final List<DepartmentDO> doList = BeanUtil.copyToList(saveList, DepartmentDO.class);
            super.saveBatch(doList, DEFAULT_BATCH_SIZE);
            final List<DepartmentVO> voList = BeanUtil.copyToList(doList, DepartmentVO.class);
            resultList.addAll(voList);
        }
        if (CollUtil.isNotEmpty(existList)) {
            final List<DepartmentVO> voList = BeanUtil.copyToList(existList, DepartmentVO.class);
            resultList.addAll(voList);
        }
        return resultList;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"department"}, allEntries = true),
            @CacheEvict(cacheNames = {"userDepartment"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true)
        }
    )
    @Override
    public boolean removeByIds(List<Long> ids) {
        List<DepartmentDO> list = super.listByIds(ids);
        if (CollUtil.isEmpty(list)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        boolean match = list.stream().anyMatch(DepartmentDO::getBuildInFlag);
        if (Boolean.TRUE.equals(match)) {
            throw new BizException(BizCodeEnum.HAS_BUILD_IN_DATA);
        }
        // 判断是否有子集
        boolean data = SqlHelper.retBool(super.count(Wrappers.lambdaQuery(DepartmentDO.class)
            .in(DepartmentDO::getParentId, ids)));
        if (data) {
            throw new BizException(MgtCodeEnum.CHILDREN_NOT_DELETED);
        }
        this.userDepartmentService.removeByDepartmentIds(ids);
        super.removeByIds(ids);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"department"}, allEntries = true),
            @CacheEvict(cacheNames = {"userDepartment"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true)
        }
    )
    @Override
    public boolean edit(DepartmentEditDTO entity) {
        DepartmentDO data = super.getById(entity.getId());
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        Long orgId = data.getOrgId();
        // 校验名称是否存在
        if (CharSequenceUtil.isNotBlank(entity.getName()) && !CharSequenceUtil.equals(data.getName(), entity.getName().trim())) {
            this.getNameIsExist(entity.getName().trim(), orgId, data.getParentId());
        }
        if (CharSequenceUtil.isNotBlank(entity.getCode()) && !CharSequenceUtil.equals(data.getCode(), entity.getCode().trim())) {
            this.getCodeIsExist(entity.getCode().trim(), orgId, data.getParentId());
        }
        if (Objects.isNull(entity.getVersion())) {
            entity.setVersion(data.getVersion());
        }
        entity.setLevel(this.getLevel(orgId, entity.getParentId()));
        final DepartmentDO model = BeanUtil.copyProperties(entity, DepartmentDO.class);
        super.updateById(model);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"department"}, allEntries = true),
            @CacheEvict(cacheNames = {"userDepartment"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true)
        }
    )
    @Override
    public boolean editStatus(Long id, EnableStatusEnum status) {
        DepartmentDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (status.equals(data.getStatus())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        DepartmentDO param = new DepartmentDO();
        param.setId(id);
        param.setStatus(status);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"department"}, allEntries = true),
            @CacheEvict(cacheNames = {"userDepartment"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true)
        }
    )
    @Override
    public boolean editBuildIn(Long id, Boolean buildInFlag) {
        DepartmentDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (buildInFlag.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        DepartmentDO param = new DepartmentDO();
        param.setId(id);
        param.setBuildInFlag(buildInFlag);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"department"}, allEntries = true),
            @CacheEvict(cacheNames = {"userDepartment"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true)
        }
    )
    @Override
    public Map<Long, Long> editInitToOrg(Long orgId, Set<Long> departmentIds) {
        Map<Long, Long> idMap = new HashMap<>(16);
        if (CollUtil.isEmpty(departmentIds)) {
            return Collections.emptyMap();
        }
        final List<DepartmentDO> entities = super.list(Wrappers.lambdaQuery(DepartmentDO.class)
            .in(DepartmentDO::getId, departmentIds).orderByAsc(DepartmentDO::getSeq));
        if (CollUtil.isEmpty(entities)) {
            return Collections.emptyMap();
        }
        // 按级别分组排序，级别为1为最顶级
        final Map<Integer, List<DepartmentDO>> groupLevelMap = entities.stream().sorted(Comparator.comparing(DepartmentDO::getSeq))
            .collect(Collectors.groupingBy(DepartmentDO::getLevel, TreeMap::new, Collectors.toCollection(ArrayList::new)));
        for (Map.Entry<Integer, List<DepartmentDO>> groupLevelMapEntry : groupLevelMap.entrySet()) {
            Integer groupLevelKey = groupLevelMapEntry.getKey();
            final List<DepartmentDO> groupLevelMapList = groupLevelMapEntry.getValue();
            if (groupLevelKey == 1) {
                final List<DepartmentDO> paramList = BeanUtil.copyToList(groupLevelMapList, DepartmentDO.class);
                this.buildInitList(orgId, null, paramList);
                final List<DepartmentDTO> dtoList = BeanUtil.copyToList(paramList, DepartmentDTO.class);
                List<DepartmentVO> parentNewtList = this.saveBatchInit(dtoList);
                final List<DepartmentDO> doList = BeanUtil.copyToList(parentNewtList, DepartmentDO.class);
                this.buildIdMap(idMap, groupLevelMapList, doList);
            } else {
                final Map<Long, List<DepartmentDO>> groupParentIdMap = groupLevelMapList.stream().sorted(Comparator.comparing(DepartmentDO::getSeq))
                    .collect(Collectors.groupingBy(DepartmentDO::getParentId, LinkedHashMap::new, Collectors.toList()));
                for (Map.Entry<Long, List<DepartmentDO>> groupParentIdMapEntry : groupParentIdMap.entrySet()) {
                    final Long parentId = groupParentIdMapEntry.getKey();
                    final List<DepartmentDO> groupParentIdMapList = groupParentIdMapEntry.getValue();
                    final Long newId = idMap.get(parentId);
                    final List<DepartmentDO> paramList = BeanUtil.copyToList(groupParentIdMapList, DepartmentDO.class);
                    this.buildInitList(orgId, newId, paramList);
                    final List<DepartmentDTO> dtoList = BeanUtil.copyToList(paramList, DepartmentDTO.class);
                    final List<DepartmentVO> childrenNewList = this.saveBatchInit(dtoList);
                    final List<DepartmentDO> doList = BeanUtil.copyToList(childrenNewList, DepartmentDO.class);
                    this.buildIdMap(idMap, groupParentIdMapList, doList);
                }
            }
        }
        return idMap;
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1", condition = "#p0 != null && #p1 != null", unless = "#result == null")
    @Override
    public List<Tree<Long>> listByOrgId(Long orgId) {
        List<DepartmentBaseTreeCheckedVO> allList = super.baseMapper.selectListByOrgId(orgId, null);
        if (CollUtil.isEmpty(allList)) {
            return null;
        }
        return this.listBaseTreeChecked(allList, null);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1", condition = "#p0 != null && #p1 != null", unless = "#result == null")
    @Override
    public List<Tree<Long>> listEnabledByOrgId(Long orgId) {
        List<DepartmentBaseTreeCheckedVO> allList = super.baseMapper.selectListByOrgId(orgId, EnableStatusEnum.ENABLE);
        if (CollUtil.isEmpty(allList)) {
            return null;
        }
        return this.listBaseTreeChecked(allList, null);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1", condition = "#p0 != null && #p1 != null", unless = "#result == null")
    @Override
    public List<Tree<Long>> listByUserId(Long orgId, Long userId) {
        List<DepartmentBaseTreeCheckedVO> allList = super.baseMapper.selectListByOrgId(orgId, EnableStatusEnum.ENABLE);
        if (CollUtil.isEmpty(allList)) {
            return null;
        }
        if (Objects.nonNull(userId)) {
            List<DepartmentBaseTreeCheckedVO> checkedList = super.baseMapper.selectListByUserId(orgId, userId);
            if (CollUtil.isNotEmpty(checkedList)) {
                allList = this.listWithChecked(allList, checkedList);
            }
        }
        return this.listBaseTreeChecked(allList, null);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public DepartmentExtendVO getDetailExtend(Long id) {
        return super.baseMapper.selectDetailById(id);
    }

    private void getNameIsExist(String name, Long orgId, Long parentId) {
        final LambdaQueryWrapper<DepartmentDO> queryWrapper = Wrappers.lambdaQuery(DepartmentDO.class)
            .eq(DepartmentDO::getOrgId, orgId)
            .eq(DepartmentDO::getName, name);
        if (Objects.nonNull(parentId)) {
            queryWrapper.eq(DepartmentDO::getParentId, parentId);
        }
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.NAME_EXIST);
        }
    }

    private void getCodeIsExist(String code, Long orgId, Long parentId) {
        final LambdaQueryWrapper<DepartmentDO> queryWrapper = Wrappers.lambdaQuery(DepartmentDO.class)
            .eq(DepartmentDO::getOrgId, orgId)
            .eq(DepartmentDO::getCode, code);
        if (Objects.nonNull(parentId)) {
            queryWrapper.eq(DepartmentDO::getParentId, parentId);
        }
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.CODE_EXIST);
        }
    }

    /**
     * 查询下一个排序号.
     *
     * @param orgId    组织主键
     * @param parentId 父类主键
     * @return Integer
     */
    private Integer getNextSeq(Long orgId, Long parentId) {
        QueryWrapper<DepartmentDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DepartmentDO::getOrgId, orgId);
        if (Objects.nonNull(parentId)) {
            queryWrapper.lambda().eq(DepartmentDO::getParentId, parentId);
        }
        queryWrapper.select("max(seq) as seq");
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    /**
     * 查询级别.
     *
     * @param orgId    组织主键
     * @param parentId 父类主键
     * @return Integer
     */
    private Integer getLevel(Long orgId, Long parentId) {
        if (Objects.isNull(parentId)) {
            return 1;
        }
        QueryWrapper<DepartmentDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DepartmentDO::getOrgId, orgId);
        queryWrapper.lambda().eq(DepartmentDO::getId, parentId);
        queryWrapper.lambda().select(DepartmentDO::getLevel);
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    private List<Tree<Long>> listBaseTreeChecked(List<DepartmentBaseTreeCheckedVO> allList, Long rootId) {
        TreeNodeConfig config = new TreeNodeConfig();
        config.setWeightKey("seq");
        return TreeUtil.build(allList, rootId, config, (object, tree) -> {
            tree.setId(object.getId());
            tree.setParentId(object.getParentId());
            tree.setWeight(object.getSeq());
            tree.setName(object.getName());
            tree.putExtra("level", object.getLevel());
            Boolean checked = object.getChecked();
            if (Objects.nonNull(checked)) {
                tree.putExtra("checked", checked);
            }
        });
    }

    private List<DepartmentBaseTreeCheckedVO> listWithChecked(
        List<DepartmentBaseTreeCheckedVO> allList,
        List<DepartmentBaseTreeCheckedVO> checkedList) {
        return allList.stream().peek(map -> checkedList.stream().filter(m -> Objects.equals(m.getId(), map.getId())).forEach(m -> {
            map.setChecked(m.getChecked());
        })).collect(Collectors.toCollection(ArrayList::new));
    }

    private void buildInitList(Long orgId, Long parentId, List<DepartmentDO> entities) {
        entities.forEach(entity -> {
            entity.setId(null);
            entity.setVersion(0);
            entity.setParentId(parentId);
            entity.setOrgId(orgId);
            entity.setRemark(MgtConstant.REMARK_INIT);
        });
    }

    private void buildIdMap(Map<Long, Long> idMap, List<DepartmentDO> oldList, List<DepartmentDO> newList) {
        oldList.forEach(oldData -> newList.forEach(newData -> {
            if (oldData.getName().equals(newData.getName())) {
                idMap.put(oldData.getId(), newData.getId());
            }
        }));
    }
}
